import 'package:flutter/material.dart';
import 'package:flutter_common/ui/scaffold.dart';
import 'package:flutter_common/ui/smart_refresh.dart';
import 'package:flutter_common/util/context_extension.dart';
import 'package:flutter_common/util/toast_util.dart';

class RefresherDemo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _State();
}

class _State extends SmartRefresherState<RefresherDemo>
    with SingleTickerProviderStateMixin {
  late TabController controller;
  List<String> items = [];
  int _page = 1;

  _State() : super(enablePullDown: true, enablePullUp: true);

  @override
  void initState() {
    super.initState();
    controller = TabController(length: 2, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return FxScaffold.Center(
      body: _body(context),
      title: 'Refresher Demo',
      onBackPressed: () => onBackPress(context),
    );
  }

  _body(BuildContext context) {
    return Column(children: [
      TabBar(
        tabs: const [
          Text("有数据"),
          Text("无数据"),
        ],
        onTap: (v) => onRefreshCallback(),
        controller: controller,
        indicatorColor: Colors.red,
        labelColor: Colors.green,
      ),
      Expanded(
        child: getSmartRefresher(context),
      )
    ]);
  }

  void onBackPress(BuildContext context) {
    ToastUtil.showToast("handle back pressed");
    context.pop();
  }

  void _onRefresh(int page) async {
    // monitor network fetch
    await Future.delayed(Duration(milliseconds: 2000));

    if (controller.index == 0) {
      if (page == 1) items.clear();
      for (int i = 0; i < 10; i++) {
        items.add(((page - 1) * 10 + i).toString());
      }
      _page = page;
    } else {
      items.clear();
    }
    finishRefresh(items.isEmpty);
  }

  @override
  Widget buildSmartRefresherBody(BuildContext context) {
    return ListView.builder(
      itemBuilder: (c, i) {
        return Card(child: Center(child: Text(items[i])));
      },
      itemExtent: 100.0,
      itemCount: items.length,
    );
  }

  @override
  void onRefreshCallback() {
    _onRefresh(1);
  }

  @override
  void onLoadMoreCallback() {
    _onRefresh(_page + 1);
  }
}
